#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void read_data(int sockfd);
size_t readn(int sockfd, char *buf, size_t bufsize);

int main()
{
	int listen_fd, conn_fd;
	socklen_t cli_len;
	struct sockaddr_in serv_addr, cli_addr;

	listen_fd = socket(AF_INET, SOCK_STREAM, 0);

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(15555);

	bind(listen_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

	listen(listen_fd, 1024);

	for(;;) {
		cli_len = sizeof(cli_addr);
		conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len);
		read_data(conn_fd);
		close(conn_fd);
	}
}


void read_data(int sockfd) {
	size_t n;
	char buf[1024];
	int times = 0;

	for (;;) {
		fprintf(stdout, "block in read\n");

		if ((n = readn(sockfd, buf, 1024) == 0)) {
			return;
		}

		times++;
		fprintf(stdout, "1K read for %d \n", times); 
		usleep(1000);
	}
}

size_t readn(int sockfd, char *buf, size_t size) {
	char *pbuf = buf;
	int length = size;

    while (length > 0) {
    	int read_len = read(sockfd, buf, length);

    	if (read_len < 0) {
    		if (errno == EINTR)
    			continue;
    		else
    			return (-1);
    	} else if (read_len == 0)
    		break;

    	length -= read_len;
    	buf += read_len;
    }

    return (size - length);
}



